$m(function(args) {
	var that = this;
	var $this = this.element;
	var pHeight = $this.parent().height();
	// 生成授权码中全部授权码状态表单
	var c_authgrid;
	var gridData = null;
	var authData = {
		removeIds: [],
		addIds: []
	};
	//左侧搜索框
	var leftSearch = $("#tempo-datasource-folder-left-search");
	//工程树
	var $Project = $("#tempo-datasource-folder-left-project");
	
	/**
	 * 初始化页面布局
	 */
	var initMainPage = function(){
		$this.height(pHeight - 4);
		$this.find('#ssc').height(pHeight - 72);
		$this.find('.sm_tab').each(function(){
			$(this).height($(this).parent().height() - 62);
		})
		$this.tabs({
			 activate: function( event, ui ) {
				var pid = ui.newPanel.attr('id');
				if(pid == 'serviceStatiscContainer'){
					initStatiscConitaner();
				}
			 }
		});

		//初始化主页面布局
		initMainLayout();

		initLeftTabs();
		
		initSericeGrid();
	}
	
	/**
	 * 初始化主体布局
	 */
	var initMainLayout = function(){
		//主布局
		$this.find('#serviceAuthContainer').layout({
			west : {
				resizable : false,
				size : '220',
				spacing_open : 1,
				closable : false
			}
		});
	}
	
	var initStatiscConitaner = function(){
		var ssc = $this.find('#ssc')
		if(!ssc.data("inited")){
			ssc.tabs({
				 activate: function( event, ui ) {
						var pid = ui.newPanel.attr('id');
						if(pid == 'serviceLogStatisccContainer'){
							initStatiscGraphConitaner();
						}
				 }
			});
			ssc.find('#serviceLogContainer').layout({
				north : {
					resizable : false,
					size : '100',
					spacing_open : 1,
					closable : false
				},
				center: {
					onresize_end: function() {
						var width = $('#mine-opt-servicelog-container').width();
						$('#mine-opt-servicelog-grid').jqGrid('setGridWidth', width, true);
					}
				}
			})
			initQuery(ssc);
			initServiceLogGrid(ssc);
			ssc.data("inited", true);
		}
	}
	
	var initStatiscGraphConitaner = function(){
		var ssc = $this.find('#serviceLogStatisccContainer')
		if(!ssc.data("inited")){
			ssc.find('#ddd').height('100%').layout({
				north : {
					resizable : false,
					size : '60',
					spacing_open : 1,
					closable : false
				}
			})
			initSqueryForm(ssc)
			graph();
			ssc.data("inited",true);
		}
	}
	
	var initQuery = function(parent){
		var form = parent.find('#queryForm');
		TempoUtils.parserUi(form,{});
		form.find('[name="starttime"]').datepicker({ 
			dateFormat : "yy-mm-dd",
			yearRange: "c-100:",
			//设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
			changeYear:true,
			changeMonth:true,
			onClose: function( selectedDate ) {
				var d = $(this).datepicker('getDate');
				if(!!d) {
					var d2 = new Date(d.getTime());
					var d2str = d2.Format('yyyy-MM-dd');
					form.find('[name="endtime"]').datepicker( "option", "minDate", d2str );
				}
			},
			onSelect: function(value){
				//connectChart();
			},
			onChangeMonthYear : function(year, month, inst){ 
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
			}
		});
		form.find('[name="endtime"]').datepicker({ 
			dateFormat : "yy-mm-dd",
			yearRange: "c-100:",
			//设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
			changeYear:true,
			changeMonth:true,
			onSelect: function(value){
			},
			onClose: function( selectedDate ) {
				var d = $(this).datepicker('getDate');
				if(!!d) {
					var d2 = new Date(d.getTime());
					var d2str = d2.Format('yyyy-MM-dd');
					form.find('[name="starttime"]').datepicker( "option", "maxDate", d2str );
				}
			},
			onChangeMonthYear : function(year, month, inst){ 
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
			}
		});
		form.find('.queryBtn').button({click:function(){
			var serviceName = form.find('[name="serviceName"]').val();
			var client = form.find('[name="client"]').val();
			var result = form.find('[name="result"]').val();
			var starttime = form.find('[name="starttime"]').datepicker('getDate');
			var endtime = form.find('[name="endtime"]').datepicker('getDate');
			var data = {
					serviceName: serviceName,
					client: client,
					result: result,
					starttime: starttime ? DateUtils.formatDate(starttime, 'yyyy-MM-dd') : null,
					endtime: endtime ? DateUtils.formatDate(endtime, 'yyyy-MM-dd') :null
			}
			parent.find('#mine-opt-servicelog-grid').datagrid('reloadGrid', data);
			return false;
		}});
		form.find('.resetBtn').button({click : function(){
			form[0].reset();
			form.find('[name="result"]').val('').selectmenu('refresh');
			return false;
		}});
	}
	
	var initSqueryForm = function(parent){
		var form = parent.find('#squeryForm');
		TempoUtils.parserUi(form,{});
		form.find('[name="result"]').val(1).selectmenu('refresh');
		form.find('[name="starttime"]').datepicker({ 
			dateFormat : "yy-mm-dd",
			yearRange: "c-100:",
			//设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
			changeYear:true,
			changeMonth:true,
			onClose: function( selectedDate ) {
				var d = $(this).datepicker('getDate');
				var d2 = new Date(d.getTime() + 24*60*60*1000);
				var d2str = d2.Format('yyyy-MM-dd');
				form.find('[name="endtime"]').datepicker( "option", "minDate", d2str );
			},
			onSelect: function(value){
//				connectChart();
			}
		});
		form.find('[name="endtime"]').datepicker({ 
			dateFormat : "yy-mm-dd",
			yearRange: "c-100:",
			//设置日期的最大时间和最小时间
			minDate : DateUtils.formatDate(new Date(new Date().getFullYear() - 100, 0, 1)),
			maxDate : DateUtils.formatDate(new Date(new Date().getFullYear() + 1, 0, 1)),
			changeYear:true,
			changeMonth:true,
			onSelect: function(value){
			},
			onClose: function( selectedDate ) {
				var d = $(this).datepicker('getDate');
				var d2 = new Date(d.getTime() - 24*60*60*1000);
				var d2str = d2.Format('yyyy-MM-dd');
				form.find('[name="starttime"]').datepicker( "option", "maxDate", d2str );
			}
		});
		form.find('.queryBtn').button({click:function(){
			var serviceName = form.find('[name="serviceName"]').val();
			var client = form.find('[name="client"]').val();
			var result = form.find('[name="result"]').val();
			var starttime = form.find('[name="starttime"]').datepicker('getDate');
			var endtime = form.find('[name="endtime"]').datepicker('getDate');
			var data = {
					serviceName: serviceName,
					client: client,
					result: result,
					starttime: starttime ? DateUtils.formatDate(starttime, 'yyyy-MM-dd') : null,
					endtime: endtime ? DateUtils.formatDate(endtime, 'yyyy-MM-dd') :null
			}
			graph(data);
			return false;
		}});
		form.find('.resetBtn').button({click : function(){
			form[0].reset();
			return false;
		}});
		$this.find('.row').height($this.find('.ddd').height()/2);
		$this.find('.row .graph').height($this.find('.ddd').height()/2 - 40)
		$this.find('.row .graph').width($this.find('.ddd').width()/2 -40)
	}
	
	var graph = function(data){
		
		//成功率
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/graph/status',
			data : data, 
			success : function(result){
				var dom = $this.find('.status');
				if(result){
					renderChart(dom[0], result);
				}
			}
		})
		//接口调用次数
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/graph/month',
			data : data, 
			success : function(result){
				var dom = $this.find('.month');
				if(result){
					renderChart(dom[0], result);
				}
			}
		})
		
		//高频调用接口次数和成功率
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/graph/g3',
			data : data, 
			success : function(result){
				var dom = $this.find('.g3');
				if(result){
					renderChart(dom[0], result);
				}
			}
		})
		
		//失败调用流程列表
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/graph/g4',
			data : data, 
			success : function(result){
				var dom = $this.find('.g4 tbody');
				dom.empty();
				if(result && result.length > 0){
					var body = '';
					for (var m = 0; m < result.length; m++) {
						var item = result[m];
						body += '<tr>';
						body += '<td>' + (m+1) + '</td>'
						body += '<td>' + item.n + '</td>'
						body += '<td>' + item.c + '</td>'
						body += '<td>' + item.r + '%</td>'
					}
					dom.html(body);
				}
			}
		})
	}
	var renderChart = function(dom, options){
		var chart = echarts.init(dom);
		chart.setOption(options);
		
	}
	
	var initServiceLogGrid = function(parent){
		parent.find('#mine-opt-servicelog-grid').datagrid({
			datatype : "json",
			url : contextPath + '/api/ai/mine/publish/listServiceLog?time=' + new Date().getTime(),
			fit:true,
			rownumbers : true,
			mtype : 'POST',
			autowidth:true,
			rownumbers : true,
			shrinkToFit : true, 
			viewrecords : true,
			striped : true,
			colNames : [ 'id', 
			             TempoUtils.locale("mine.publish-mine-service-grid-col-serviceid"),//'服务名称'
			             TempoUtils.locale("mine.fuwudizhi"),
			             TempoUtils.locale("mine.diaoyongxitong"),
			             TempoUtils.locale("mine.diaoyongriqi"),
			             TempoUtils.locale("mine.diaoyongjieguo"),
			             TempoUtils.locale("mine.xiangxirizhi"),
			             ],//'操作'
			             colModel : [{
			            	 name : 'id',
			            	 index : 'id',
			            	 hidden : true,
			            	 sortable : false
			             },{
			            	 name : 'serviceName',
			            	 index : 'serviceName',
			            	 width : 80,
			            	 sortable : false
			             },{
			            	 name : '',
			            	 index : '',
			            	 formatter : function(obj, grid, rows, state) {
			            		 var url = rows.serviceId;
			            		 if(url && !!!rows.type){
			            			 return contextPath + "/webapi/minews/execute/" + url
			            		 }
			            		 return  "--";
			            	 },
			            	 sortable : false
			             },{
			            	 name : 'client',
			            	 index : 'client',
			            	 sortable : false,
			            	 width : 120,
			            	 sortable : false
			             },{
			            	 name : 'runTime',
			            	 index : 'runTime',
			            	 formatter : function(obj, grid, rows, state) {
			            		 var runTime = rows.runTime;
			            		 if(runTime){
			            			 return DateUtils.formatDateTime(runTime, 'yyyy-MM-dd hh:mm:ss');

			            		 }
			            		 return  "";
			            	 },
			            	 width : 80,
			            	 sortable : false
			             },{
			            	 name : 'runResult',
			            	 index : 'runResult',
			            	 sortable : false,
			            	 width : 120, 
			            	 formatter : function(obj, grid, rows, state) {
			            		 var success = rows.runResult
			            		 if(success == 1){
			            			 return TempoUtils.locale("mine.chenggong");
			            		 }
			            		 if(success == 0){
			            			 return TempoUtils.locale("mine.shibai");
			            		 }
			            		 return TempoUtils.locale("mine.zhengzaizhixing");
			            	 },
			            	 width : 80
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 align : 'left',
			            	 width : 40,
			            	 formatter : function(obj, grid, rows, state) {
			            		if(!!rows.type) return '--';
			            		return "<a href='javascript:;void(0)'  rowid='" + rows.id + "' class='viewlog'>"+TempoUtils.locale("mine.mine_log")+"</a>";
			            	 }
			             }
			             ],
			             loadComplete : function(datas){
			            	 var rows = datas.rows;
			            	 $(this).data('rows', rows);
			            	 $(this).find('.viewlog').each(function(index, domEle){
			 					$(domEle).off('click').on('click',function(){
			 						var logid = $(this).attr('rowid');
			 						downloadLog(logid, null, null);
			 					})
			 				});
			             },
			             pagination : true
		
		})
	}


	//初始化左侧工程搜索
	var initProjectSearchbar = function(){
		leftSearch.searchbar({
			isEnter:true,
			placeholder:TempoUtils.locale("mine.susougongcheng"),
			onSearch:function(text){
				$Project.find('.tempo-tree-item').removeClass('tempo-tree-item-select').hide();
				var items = $Project.find('.tempo-tree-content-group .tempo-tree-item:first-child');
				if(items && items.size() > 0){
					items.each(function(){
						var d = $(this).data('data');
						var name = d.NAME;
						if(name.toLowerCase().indexOf(text.toLowerCase()) != -1){
//							$(this).addClass('tempo-tree-item-select');
							$(this).show();
							var rootid = $(this).parent().prev('.tempo-tree-item').attr('menuid')
							if(rootid){
								$Project.tree('expandNodeByMenuId', rootid);
							}
							return;
						}
					})
				}
			}
		});
	}
	
	
	//初始化左侧标签
	var initLeftTabs = function(filterVal){
		initProjectSearchbar();
				$Project.tree({
					idField:"ID",
					url : contextPath + '/api/ai/mine/publish/listAllProjectsMine?date=' + new Date().getTime(),
					textField:'NAME',
					multiSelect:false,
					onClickItem : function(data){
						if(data.TYPE == 'mining'){
							$('#mine-opt-service-grid').datagrid('reloadGrid', {themeId : data.ID});
						}
					}
				});
	}
	
	//初始化服务列表
	var initSericeGrid = function(analyseId){
		var height = pHeight-155;//空出查询框的高度
		that.grid = $('#mine-opt-service-grid').datagrid({
			datatype : "json",
			url : contextPath + '/api/ai/mine/publish/listService?time=' + new Date().getTime(),
			postData : {themeId : analyseId},
			height : height,
			fit:true,
			rownumbers : true,
			mtype : 'POST',
			autowidth:true,
			rownumbers : true,
			shrinkToFit : true, 
			viewrecords : true,
			striped : true,
			colNames : [ 'id', 
			             TempoUtils.locale("mine.publish-mine-service-grid-col-serviceid"),//'服务名称'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-creator"),//'创建者'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-relatedflow"),//'涉及流程'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-authstatus"),//'授权状态'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-log"),//'日志'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-status"),//'运行状态'
			             TempoUtils.locale("mine.publish-mine-service-grid-col-opt")
			             ],//'操作'
			             colModel : [{
			            	 name : 'id',
			            	 index : 'id',
			            	 hidden : true,
			            	 sortable: false
			             },{
			            	 name : 'name',
			            	 index : 'name',
			            	 sortable: false
			             },
			             {
			            	 name : 'creatorName',
			            	 index : 'creatorName',
			            	 sortable: false
			             },{
			            	 name : 'flowName',
			            	 index : 'flowName',
			            	 sortable: false
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 width : 120, 
			            	 formatter : function(obj, grid, rows, state) {
			            		 var success = rows.auth;
			            		 return  success ? TempoUtils.locale("mine.publish-mine-service-authed") : TempoUtils.locale("mine.publish-mine-service-noauthed");
			            	 }
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 align : 'left',
			            	 width : 40,
			            	 formatter : function(obj, grid, rows, state) {
			            		 var logs = rows.logs;
			            		 if(logs && logs.length > 0){
			            			 return "<a href='javascript:;void(0)' rowid='" + rows.id + "' class='viewlog'>"+TempoUtils.locale("mine.publish-mine-job-log-view")+"</a>";
			            		 }
			            		 return '';
			            	 }
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 width : 120, 
			            	 formatter : function(obj, grid, rows, state) {
			            		 var success = rows.successCount || 0;
			            		 var fail = rows.failedCount || 0;
			            		 return  TempoUtils.locale("mine.publish-mine-job-exe-success") +"<span style='color:green'>" + success + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time")+ "　" + TempoUtils.locale("mine.publish-mine-job-exe-fail") + "<span style='color:red'>" + fail + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time");
			            	 }
			             },{
			            	 name : '',
			            	 index : '',
			            	 sortable : false,
			            	 width : 100,
			            	 align : 'center',
			            	 buttons:[
			            	          {
			            		 id : "edit",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-edit",
			            		 title: TempoUtils.locale("mine.publish-btn-edit"),
			            		 click:function(e,dt){	     
			            			 var rowid = dt.rowId;
			            			 var row = dt.rowData;
			            			 initAuthDialog(row);
			            		 }
			            	 },
			            	 {
			            		 id : "link",
			            		 icon:"ui-icon tempo-ui-icon tempo-ui-icon-download",
			            		 title: TempoUtils.locale("mine.publish-btn-download"),
			            		 click:function(e,dt){
			            			 var rowData = dt.rowData;
			            			 $("<div/>").confirm({
			            					msg :  TempoUtils.locale("mine.publish-mine-download-msg"),
			            					height : 160,
			            					width : 260,
			            					ok : function(){
			            						/**
			            						 * 下载示例代码
			            						 */
			            						var codeUrl = contextPath + '/api/ai/mine/sync/clientcode';
			            						if(rowData.type != 'sync') {
			            							codeUrl = contextPath + '/api/ai/mine/async/clientcode';
			            						}
			            						TempoUtils.download({
			            							url: codeUrl,
			            							data: {
			            								id: rowData.id,
			            								flowid: rowData.flowid
			            							}
			            						});
			            					}
			            				});
			            		 }
			            	 }]
			             }
			             ],
			             loadComplete : function(datas){
			            	 var rows = datas.rows;
			            	 $(this).data('rows', rows);
			            	 bindServiceGridEvent.apply(that);
			             },
			             pagination : true
		});
	}
	
	/**
	 * 服务列表事件
	 */
	var bindServiceGridEvent = function(){
		var grid = $('#mine-opt-service-grid');
		grid.find(".viewlog").each(function(){
			var rowid = $(this).attr('rowid');
			var row = null;
			var rows = grid.data('rows');
			if(rows && rows.length > 0){
				for (var m = 0; m < rows.length; m++) {
					if(rowid == rows[m].id){
						row = rows[m];
					}
				}
			}
			var logs = row.logs;
			var content;
			if(logs && logs.length > 0){
				var logele = $('<ul>').css({
					'list-style-type' : 'none'
				});
				for (var i = 0; i < logs.length; i++) {
					var log = logs[i];
					var date = new Date(parseFloat(log.runTime));
					var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
					var runResult = log.runResult;
					var icon = "ui-icon ui-icon-document";
					if (runResult != null) {
						if (runResult == 0) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-errorprompt";
						} else if (runResult == 1) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-check-thin";
						}
					}
					var liele = $('<li class="logitem">').attr('logid', log.id).attr('runResult', runResult).attr('name', logName);
					var liicon = $("<span>").addClass(icon).appendTo(liele);
					var lilabel = $("<label>").text(logName).appendTo(liele);
					logele.append(liele);
				}
				content = $('<div>').append(logele).html();
			}
			$(this).webuiPopover({
				trigger : 'hover',
				title : '',
				cache : false,
				placement : 'right',
				width : 180,		
				closeable : false,
				arrow : true,
				content : content
			})
			$(this).on('shown.webui.popover', function(){
				$('.logitem').each(function(index, domEle){
					$(domEle).off('click').on('click',function(){
						var logid = $(this).attr('logid');
						var runResult = $(this).attr('runResult');
						var name = $(this).attr('name');
						downloadLog(logid, name, runResult);
					})
				});
			});
		});
	}
	
	/**
	 * 下载任务日志
	 */
	var downloadLog = function(id, name,runResult){
		TempoUtils.downLoadFile({
			url: contextPath + "/api/ai/mine/publish/downloadServiceLog",
			data : {
				id : id,
				name : name,
				runResult : runResult
			}
		});
	}
	
	var initAuthDialog = function(service){
		var dialog = $('#tempo-mine-flow-service-dialog').clone().appendTo('body');
		// 初始化id
		authData.removeIds = [];
		authData.addIds = [];
		dialog.dialog({
			width : 650,
			minHeight: 350,
			autoOpen : false,
			title: TempoUtils.locale("mine.fuwushouquan"),
			modal:true,
			resizable: false,
			close:function(){
				dialog.dialog("destroy");
				dialog.remove();
			},
			buttons:[{
				text: TempoUtils.locale('mine.publish-dialog-sure'),
				click:function(){
					saveServiceAuth(dialog, service);
				}
			},{
				text:TempoUtils.locale('mine.publish-dialog-cancel'),
				click:function(){
					dialog.dialog("destroy");
					dialog.remove();
					
				}
			}]
		});
		dialog.dialog('open');
		initAuthGrid(dialog, service);
	}
	/**
	 * 保存服务信息
	 */
	var saveServiceAuth = function(dialog, service){
		var mask = $("<div/>").tempoprogressbar();
		var authgrid = dialog.find("#authgrid");
		var auths = authgrid.datagrid('getRowData');
		var authArr = [];
		var codes = [];
		if(auths && auths.length > 0){
			for (var m = 0; m < auths.length; m++) {
				authArr.push(auths[m].id);
				codes.push(auths[m]);
			}
		};
		if(authData.addIds.length == 0 && authData.removeIds.length == 0) {
			mask.tempoprogressbar("close");
			dialog.dialog("destroy");
			dialog.remove();
			Eventbus.trigger('authorize-save.mine', codes);
			return ;
		}

		$.ajax({
			url : contextPath + "/api/ai/mine/webapi/save-auth",
			data : {
				serviceid  : service.id,
				addIds: authData.addIds.join(","),
				removeIds: authData.removeIds.join(",")
			},
			success : function(result) {
				mask.tempoprogressbar("close");
				dialog.dialog("destroy");
				dialog.remove();
				//$('#mine-opt-service-grid').datagrid('reloadGrid');
				Eventbus.trigger('authorize-save.mine', codes);
			}
		})
	}

	
	/**
	 * 服务对应的授权列表
	 */
	var initAuthGrid = function(dialog, service) {
		var authgrid = dialog.find('table');
		authgrid.datagrid({
			datatype : "local",
			pagination : false,
			rowNum : 100000,
			width : 600,
			rownumbers : true,
			multiselect : true,
			shrinkToFit : true,
			height : 170,
			colNames : [ 'id',TempoUtils.locale("mine.clientName"), TempoUtils.locale("mine.kehubiaoshi"),TempoUtils.locale("mine.diaoyongma"), "描述"],
			colModel : [ {
				name : 'id',
				index : 'id',
				hidden : true
			} , {
				name : 'name',
				index : 'name',
				sortable : false
			}, {
				name : 'key',
				index : 'key'
			}, {
				name : 'secret',
				index : 'secret'
			} , {
				name : 'description',
				index : 'description',
				sortable : false
			} ],
			toolbar : [ /*{
				id : "createAuth",
				text :TempoUtils.locale("mine.shengchengshouquanma"),
				icon : "",
				click : function() {
					createAuth(dialog)
				}
			}, */{
				id : "newAuth",
				text : TempoUtils.locale("mine.xinzengshouquanma"),
				icon : "",
				click : function() {
					newAuth(dialog)
				}
			}, {
				id : "cancelAuth",
				text : TempoUtils.locale("mine.quxiaoshouquanma"),
				icon : "",
				click : function() {
					cancelAuth(dialog)
				}
			} ]
		});
		$('#createAuth').hide();
		var progress = $("<div/>").tempoprogressbar();
		if (service) {
			$.ajax({
				url : contextPath + "/api/ai/mine/webapi/list-auth-app?date="
						+ new Date().getTime(),
				data : {
					serviceid : service.id
				},
				success : function(result) {
					authgrid.datagrid('clearGridData');
					authgrid.datagrid('addJSONData', result.data);
				}
			})
		}
		$.ajax({
			url : contextPath + "/api/ai/app/identification/sys",
			contentType: 'application/x-www-form-urlencoded',
			success : function(rs) {
				var result = rs.data;
				// 判断是否为系统管理员
				if (result == true) {
					$('#createAuth').show();
				}
				progress.tempoprogressbar("destroy");
			}
		})

	}


	/**
	 * 新增授权
	 */
	var newAuth = function(dialog){
		$.ajax({
			url : contextPath + "/api/ai/mine/webapi/list-all-app?date=" + new Date().getTime(),
			data : { },
			type: 'POST',
			success : function(result) {
				if(result && result.success) {
					var authgrid = dialog.find("#authgrid");
					var auths = authgrid.datagrid('getRowData');
					if(auths && auths.length > 0){
						var arr = result.data.filter(function(item){
							for (var m = 0; m < auths.length; m++) {
								if(auths[m].id == item.id){
									return false;
								}
							}
							if("SYSTEM"==item.type){
								return false;
							}
							return true;
						})
						showAuthGrid(dialog, arr);
					}else{
						var arr = result.data.filter(function(item){
							if("SYSTEM"==item.type){
								return false;
							}
							return true;
						})
						showAuthGrid(dialog, arr);
					}
					
				}else{
					$("<div/>").alert({
						msg : TempoUtils.locale("mine.shouquanmaerror")
					});
				}
			}
		})
	}

	/**
	 * 新增授权窗口
	 */
	var showAuthGrid = function(pdialog, datas){
		var dialog = $("<div/>",{
			"id" : 'auth_Dialog'
		});
		var grid = $('<table>').addClass('auth_Grid').appendTo(dialog);
		dialog.dialog({
			width : 500,
			height : 350,
			autoOpen:true,
			title : TempoUtils.locale("mine.shouquanliebiao"),
			modal:true,
			close:function(){
				dialog.dialog("destroy");
			},
			open:function(){
				initAuthCodeGrid(dialog, datas);
			},
			buttons:[{
				text: TempoUtils.locale('mine.publish-dialog-sure'),
				click:function(){
					saveAuthConfig(pdialog, dialog);
					dialog.dialog("close");
				}
			},{
				text:TempoUtils.locale('mine.publish-dialog-cancel'),
				click:function(){
					dialog.dialog("close");
				}
			}]
		});
	}

	/**
	 * 新增授权窗口 保存
	 */
	var saveAuthConfig = function(pdialog, dialog){
		var grid = dialog.find('.auth_Grid');
		var rowData = grid.datagrid("getSelectRowData");
		if(rowData !=null && rowData.length > 0){
			var authGrid = pdialog.find('#authgrid');
//			authGrid.datagrid('clearGridData');
			authGrid.datagrid('addJSONData', rowData);
			var ids = rowData.map(function(r){ return r.id; });
			// 过滤添加未删除的id
			var addIds = ids.filter(function (value) {
				return authData.removeIds.filter(function (x) {
					return x == value;
				}).length == 0;
			});
			// 移除已经删除的id，防止重复删除添加
			var removeIds = authData.removeIds.filter(function (value) {
				return ids.filter(function (x) {
					return x == value;
				}).length == 0;
			});
			authData.removeIds = removeIds;
			authData.addIds.push(addIds);
		}
	}

	/**
	 * 新增授权窗口 列表
	 */
	var initAuthCodeGrid = function(dialog, datas){
		var grid = dialog.find('.auth_Grid');
		grid.data('data', datas);
		grid.datagrid({
			datatype:"local",
			data:datas,
			pagination : false,
			rowNum:100000,
			multiselect : true, 
			fit:true,
			rownumbers : true,
			colNames : [ 'id',
				'key',
				'secret',
				'证书名称',
			    '描述'
			],
			 colModel : [{
				 name : 'id',
				 index : 'id',
				 hidden : true
			 },{
				 name : 'key',
				 index : 'key',
				 hidden : true
			 },{
				 name : 'secret',
				 index : 'secret',
				 hidden : true
			 },{
				 name : 'name',
				 index : 'name'
			 },{
				 name : 'description',
				 index : 'description'
			 }
			]
		});
	}

	/**
	 * 服务授权列表 取消授权
	 */
	var cancelAuth = function(dialog){
		var that = this;
		var grid = dialog.find('#authgrid');
		var rowData = grid.datagrid("getSelectRowData");
		if(rowData && rowData.length > 0){
			
			$("<div>").confirm({
				msg : TempoUtils.locale("mine.shifouquanxiaoshouquan"),
				ok :function(){
					var selectRowIds = TempoUtils.clone(grid.datagrid("getGridParam","selarrrow"));
					if(selectRowIds && selectRowIds.length > 0){
						for (var m = 0; m < selectRowIds.length; m++) {
							var rowid = selectRowIds[m];
							var row = grid.datagrid('getRowData', rowid);
							authData.removeIds.push(row.id);
							grid.datagrid('delRowData', rowid);
							authData.addIds.filter(function(x){ return x != row.id });
						}
					}
				}
			});
		}else{
			$("<div>").alert({
				msg : TempoUtils.locale("mine.zhishaoxuanzeyitiaoshuju")
			});
		}
	}


	
	/**
* 生成授权码
* 
*/
var createAuth = function(dialog) {
var createAuthdialog = $("<div/>", {
	"id" : 'create_auth_Dialog',
	"style" : "overflow-y:auto"
});
var grid = $('<table>').addClass('create_auth_Grid').appendTo(
		createAuthdialog);
createAuthdialog
		.dialog({
			width : 680,
			height : 600,
			autoOpen : true,
			title : TempoUtils.locale("mine.huoqudiaoyongma"),
			modal : true,
			close : function() {
				createAuthdialog.dialog("destroy");
			},
			open : function() {
				createAuthdialog
						.append("<div class='tempo-webapi-apiinfo-container'>"
								+ "<table align='center' class='formLayout'><tr><td class='formLayoutTit'><label>"+TempoUtils.locale("mine.jiekoumingcheng")+"</label></td>" +
										"<td>"+TempoUtils.locale("webapi.flowPublishServiceInvokeApi_tip1")+"</td></tr>"
								+ "<tr><td class='formLayoutTit'><label>"+TempoUtils.locale("mine.shuoming")+"</label></td>" +
										"<td>"+TempoUtils.locale("webapi.flowPublishServiceInvokeApi_tip4")+"</td></tr>"
								+ "</table>");
				createAuthdialog
						.append("<form class='clientCodeForm'style='width: 360px;'><table align='center' class='formLayout'>"
								+ "<tr><td class='formLayoutTit'><label>"+TempoUtils.locale("mine.kehubiaoshi")+"</label></td>"
								+ '<td><input type="text" class="validatebox" name="clientCode" ui-role="validatebox" ui-options="valids:[/^[A-Za-z0-9]{6,10}$/],required:true,autofill:false,tip:\''+TempoUtils.locale("mine.client_code_tip")+'\'" style="width:150px;" /></td>'
								+ "<td class='formLayoutTit'><label>"+TempoUtils.locale("mine.clientName")+"</label></td>"
								+ '<td><input type="text" class="validatebox" name="clientName" ui-role="validatebox" ui-options="maxLength:10,required:true,autofill:false" style="width:150px;" /></td>'
								+ "<td><button id='genSkCode' type='button' class='tempo-button ui-button ui-corner-all ui-widget' style='height:24px;line-height:24px;margin-top:-4px;margin-left:4px;width:100px'>"+TempoUtils.locale("mine.huoqudiaoyongma")+"</button></td></tr>"
								+ "<tr><td class='formLayoutTit'><label>"+TempoUtils.locale("mine.diaoyongma")+"</label></td><td id='skCode'>&nbsp;</td> </tr>"
								+ "</table></form></div>");
				createAuthdialog
						.append("<div class='tempo-webapi-code-gridcontainer'><table id='tempo-webapi-code-grid'></table></div>");
				
				TempoUtils.parserUi(createAuthdialog.find("form"), {});
				$("#genSkCode").click(function() {
					genSkCode();
				});
				renderGrid("flowPublishServiceInvokeApi",createAuthdialog);
			},
			buttons : [ {
				text : TempoUtils.locale('mine.publish-dialog-sure'),
				click : function() {
					createAuthdialog.dialog("close");
				}
			}, {
				text : TempoUtils.locale('mine.publish-dialog-cancel'),
				click : function() {
					createAuthdialog.dialog("close");
				}
			} ]
		});

}

		/**
		* 生成调用码
		*/
		function genSkCode() {
		var form = $(".clientCodeForm");
		
		var formData = TempoUtils.getRecord(form);
		var reg = RegExp(/^[A-Za-z0-9]{6,10}$/)
		if (!formData.clientCode.match(reg)) {
			showTip(TempoUtils.locale("mine.errortip"));
			return;
		}
		if(formData.clientName.trim() == ""){
			showTip(TempoUtils.locale("mine.clientNameNull"));
			return;
		}
		formData.apiId = "flowPublishServiceInvokeApi";
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url : contextPath + "/api/ai/webcode/gen",
			data : {
				apiId : "flowPublishServiceInvokeApi",
				clientCode : formData.clientCode
			},
			type : 'post',
			dataType : 'json',
			complete : function() {
				progress.tempoprogressbar("destroy");
			},
			success : function(result) {
				$("#skCode").html(result.data);
				isExists("flowPublishServiceInvokeApi", formData.clientCode,formData.clientName)
						.then(function(r){
							if(r){
								TempoUtils.showTip(TempoUtils.locale("mine.clientCodeExist"));
							}
						},function(r){
							if(!r){
								save(formData,result.data);
							}else{
								TempoUtils.showTip(TempoUtils.locale("mine.clientNameExist"));
							}
						});
			},
			error : function() {
			}
		});
		}
		
		/**
		* 渲染表格
		*/
		function renderGrid(apiId, dialog) {
		c_authgrid = dialog.find('#tempo-webapi-code-grid');
		c_authgrid
				.datagrid({
					url : contextPath + "/api/ai/webcode/list-apicode-infos",
					datatype : 'json',
					fit : true,
					rownumbers : true,
					multiselect : false,
					separator : false,
					rowNum : 1000,
					postData : {
						apiId : apiId
					},
					colNames : [ 'id', 'apiId', TempoUtils.locale("mine.kehubiaoshi"), TempoUtils.locale("mine.diaoyongma"),TempoUtils.locale("mine.clientName"), TempoUtils.locale("mine.publish-mine-job-grid-col-status"), TempoUtils.locale("mine.publish-mine-job-grid-col-opt") ],
					colModel : [
							{
								name : 'id',
								hidden : true
							},
							{
								name : 'apiId',
								hidden : true
							},
							{
								name : 'clientCode',
								sortable : false
							},
							{
								name : 'skCode',
								sortable : false
							},
							{
								name : 'clientName',
								sortable : false
							},
							{
								name : 'status',
								sortable : false,
								formatter : function(val) {
									return val == '1' ? TempoUtils.locale("mine.qiyong") : TempoUtils.locale("mine.jinyong");
								}
							},
							{
								name : 'action',
								buttons : [
										{
											id : 'disable',
											title : TempoUtils.locale("mine.jinyong"),
											icon : 'ui-icon tempo-ui-icon tempo-ui-icon-disabled',
											click : function(e, dt) {
												var code = dt.rowData.clientCode
												$.ajax({
													url : contextPath + "/api/ai/mine/publish/checkAuthCode",
													data : {
														authid:code
													},
													success : function(result) {
														if(!result){
															updateStatus(dt.rowData.apiId,code,false);
														}else{
															$("<div/>").confirm({
																title :  TempoUtils.locale("mine.prompt"), 
																msg :  TempoUtils.locale("mine.authId_disable_tip"),
																height : 240,
																width : 300,
																ok : function(){
																	var process = $("<div/>").tempoprogressbar();
																	updateStatus(dt.rowData.apiId,code,false);
																}
															});
														}
													}
												})
											},
											beforeAdd : function(rowId, rowData) {
												return rowData.status == "1";
											}
										},
										{
											id : 'enable',
											title : TempoUtils.locale("mine.qiyong"),
											icon : 'ui-icon tempo-ui-icon tempo-ui-icon-lock',
											beforeAdd : function(rowId, rowData) {
												return rowData.status == "0";
											},
											click : function(e, dt) {
												updateStatus(dt.rowData.apiId,
														dt.rowData.clientCode,
														true);
											}
										},
										{
											id : 'remove',
											title : TempoUtils.locale("mine.mine_del"),
											icon : 'ui-icon tempo-ui-icon tempo-ui-icon-remove',
											click : function(e, dt) {
												var code = dt.rowData.clientCode
												$.ajax({
													url : contextPath + "/api/ai/mine/publish/checkAuthCode",
													data : {
														authid:code
													},
													success : function(result) {
														if(!result){
															removeClientCode(dt.rowData.apiId,code); 
														}else{
															$("<div/>").confirm({
																title :  TempoUtils.locale("mine.prompt"), 
																msg :  TempoUtils.locale("mine.authId_delete_tip"),
																height : 240,
																width : 300,
																ok : function(){
																	var process = $("<div/>").tempoprogressbar();
																	removeClientCode(dt.rowData.apiId,code); 
																}
															});
														}
													}
												})
											}
										} ]
							} ],
					fit : true,
					loadComplete : function(xhr) {
						gridData = xhr.rows;
					}
				})
		}
		
		function save(formData, skCode) {
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url : contextPath + "/api/ai/webcode/save",
			type : 'post',
			data : {
				apiId : formData.apiId,
				clientCode : formData.clientCode,
				clientName : formData.clientName,
				skCode : skCode,
				status : 1,
				desc : ""
			},
			success : function(result) {
				progress.tempoprogressbar("destroy");
				if(result){
					c_authgrid.datagrid("reloadGrid");
				}
			},
			error : function() {
				progress.tempoporogressbar("destroy");
			}
		});
		}
		
		/**
		* 判断编码是否已存在
		*/
		function isExists(apiId, code,name) {
			if(gridData!=null){
				return new Promise(function(resolve,reject){
					var exist = false;
					var tagName = false;
					for(var i=0,len=gridData.length;i<len;i++){
						if(gridData[i].clientCode ===code){
							exist = true;
							break;
						}
						if(gridData[i].clientName === name){
							tagName = true;
							break;
						}
					}
					if(exist){
						resolve(exist);
					}else{
						reject(tagName);
					}
				})	
			}else{
				return new Promise(function(resolve,reject){
					var progress = $("<div/>").tempoprogressbar();
					$.ajax({
						url:contextPath+'/api/ai/webcode/exist',
						type:'post',
						dataType:'json',
						data:{
							apiId:apiId,
							code:code
						},
						success:function(result){
							reject(result.data);
						},
						error:function(e){
							reject(e);
						}
					}).done(function(){
						progress.tempoprogressbar("destroy");
					})
				});
			}
		}
		
		/**
		* 更新状态
		*/
		function updateStatus(apiId, clientCode, status) {
		var progress = $("<div/>").tempoprogressbar();
		//校验调用码是否被调用
		$.ajax({
			url : contextPath + "/api/ai/webcode/update",
			data : {
				apiId : apiId,
				clientCode : clientCode,
				status : status
			},
			type : 'post',
			success : function(result) {
				if (result) {
					c_authgrid.datagrid("reloadGrid");
				}
			}
		}).done(function() {
			progress.tempoprogressbar("destroy");
		})
		}
		
		/**
		* 删除客户端调用码
		*/
		function removeClientCode(apiId, clientCode) {
		var progress = $("<div/>").tempoprogressbar();
		//校验调用码是否被调用
		$.ajax({
			url : contextPath + "/api/ai/webcode/remove-client-code",
			data : {
				apiId : apiId,
				clientCode : clientCode
			},
			type : 'post',
			success : function(result) {
				if (result) {
					c_authgrid.datagrid("reloadGrid");
				}
			}
		}).done(function() {
			progress.tempoprogressbar("destroy");
		})
		}
		var showTip = function(msg) {
		$("<div/>").alert({
			msg : msg,
			title : TempoUtils.locale("mine.prompt")
		});
	}
	if(!args || args.load) {
		initMainPage();
	}
	
	Eventbus.one('authorize-service.mine', initAuthDialog);
});	